<route lang="jsonc">
{
  "layout": "default",
  "style": {
    "navigationBarTitleText": "用户登录"
  }
}
</route>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import { getCode } from '@/api/login'
import { useLogin } from '@/hooks/useLogin'
import { useUserStore } from '@/store'
import { isH5, isMpWeixin } from '@/utils/platform'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'Login',
})

const userStore = useUserStore()
const loading = ref(false)
const formData = reactive({
  phone: '' as string,
  verifyCode: '' as string,
})

// 使用登录钩子
const { getPhoneNumber, getSendCode, mobileLogin } = useLogin({})

// 验证码相关
const countdown = ref<number>(60)
const isSendingCode = ref(false)
const timer = ref<number | null>(null)

// 重定向信息
const redirect = ref('')

// 微信平台信息
const showWechatLogin = computed(() => isMpWeixin)
const showAccountLogin = ref(false)

// 监听页面加载
onLoad((options) => {
  if (options.redirect)
    redirect.value = decodeURIComponent(options.redirect)
})

// 开始倒计时
function startCountdown() {
  countdown.value = 60
  isSendingCode.value = true

  timer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      if (timer.value !== null) {
        clearInterval(timer.value)
        isSendingCode.value = false
      }
    }
  }, 1000) as unknown as number
}

// 发送验证码
async function sendVerifyCode() {
  console.log('发送验证码', formData.phone)

  if (!formData.phone) {
    toast.warning('请输入手机号')
    return
  }
  if (!/^1[3-9]\d{9}$/.test(String(formData.phone))) {
    toast.warning('请输入正确的手机号')
    return
  }
  try {
    isSendingCode.value = true
    const success = await getSendCode(formData.phone)

    if (success) {
      startCountdown()
    }
    else {
      isSendingCode.value = false
    }
  }
  catch (error) {
    console.error('发送验证码失败', error)
    toast.error('发送验证码失败，请稍后重试')
    isSendingCode.value = false
  }
}

// 手机号验证码登录
async function handlePhoneCodeLogin() {
  if (!formData.phone) {
    toast.warning('请输入手机号')
    return
  }
  if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
    toast.warning('请输入正确的手机号')
    return
  }

  if (!formData.verifyCode) {
    toast.warning('请输入验证码')
    return
  }

  try {
    loading.value = true
    // 执行登录
    const success = await mobileLogin({
      mobile: formData.phone,
      smsCode: formData.verifyCode,
      clientInfoType: "20",
      roleType: "20",
      fromInviteCode: "",
    })

    if (success === 'success') {
      // 登录成功后处理
      handleLoginSuccess()
    }
  }
  catch (error) {
    console.error('登录失败', error)
    toast.error('登录失败，请稍后重试')
  }
  finally {
    loading.value = false
  }
}

// 处理微信手机号授权登录
async function handlePhoneLogin(e: any) {
  try {
    loading.value = true

    // 使用useLogin中的getPhoneNumber方法
    const result = await getPhoneNumber(e)
    console.log('result', result)
    if (result === 'success') {
      // 登录成功后处理
      handleLoginSuccess()
    }
  }
  catch (error) {
    console.error('手机号登录失败', error)
    toast.error('手机号登录失败，请稍后重试')
  }
  finally {
    loading.value = false
  }
}

// 登录成功后的处理
function handleLoginSuccess() {
  toast.success('登录成功')

  // 如果有重定向地址，则跳转到重定向地址
  if (redirect.value) {
    uni.reLaunch({
      url: redirect.value,
    })
  }
  else {
    // 否则返回上一页或跳转到首页
    const pages = getCurrentPages()
    if (pages.length > 1) {
      uni.navigateBack()
    }
    else {
      uni.switchTab({
        url: '/pages/index/index',
      })
    }
  }
}

// 切换登录方式
function toggleLoginMethod() {
  showAccountLogin.value = !showAccountLogin.value
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer.value !== null) {
    clearInterval(timer.value)
    timer.value = null
  }
})
</script>

<template>
  <view class="login-container">
    <view class="logo-container">
      <image class="logo" src="/static/logo.svg" mode="aspectFit" />
      <text class="title">
        欢迎登录
      </text>
    </view>

    <!-- 手机号验证码登录表单 -->
    <view v-if="showAccountLogin" class="login-form">
      <view>
        <wd-input
          v-model="formData.phone"
          placeholder="请输入手机号"
          :maxlength="11"
          clearable
          type="number"
        >
        </wd-input>
      </view>

      <view class="mt-20rpx">
        <wd-input
          v-model="formData.verifyCode"
          placeholder="请输入验证码"
          :maxlength="6"
          clearable
        >
          <template #suffix>
            <wd-button
              :class="{ disabled: isSendingCode }"
              @tap="isSendingCode ? null : sendVerifyCode()"
            >
              {{ isSendingCode ? `${countdown}s后重新获取` : '获取验证码' }}
            </wd-button>
          </template>
        </wd-input>
      </view>
      <button
        class="login-btn account-btn"
        :disabled="loading"
        :loading="loading"
        @tap="handlePhoneCodeLogin"
      >
        登录
      </button>

      <view v-if="showWechatLogin" class="switch-login">
        <text @tap="toggleLoginMethod">
          使用微信一键登录
        </text>
      </view>
    </view>

    <!-- 微信登录 -->
    <view v-if="showWechatLogin && !showAccountLogin" class="wechat-login">
      <!-- 手机号一键登录按钮 -->
      <button
        class="login-btn wechat-btn phone-btn"
        open-type="getPhoneNumber"
        :disabled="loading"
        :loading="loading"
        @getphonenumber="handlePhoneLogin"
      >
        <text class="iconfont icon-phone" />
        手机号一键登录
      </button>

      <view class="switch-login">
        <text @tap="toggleLoginMethod">
          使用手机号验证码登录
        </text>
      </view>
    </view>

    <view class="footer">
      <text>登录即表示同意</text>
      <navigator url="/pages/agreement/user" class="link">
        《用户协议》
      </navigator>
      <text>和</text>
      <navigator url="/pages/agreement/privacy" class="link">
        《隐私政策》
      </navigator>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.login-container {
  padding: 60rpx 50rpx;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  box-sizing: border-box;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80rpx;
  margin-top: 60rpx;
}

.logo {
  width: 180rpx;
  height: 180rpx;
  margin-bottom: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.login-form,
.wechat-login {
  width: 100%;
}

.login-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  border-radius: 45rpx;
  margin-top: 30rpx;
  margin-bottom: 20rpx;
  font-size: 32rpx;
  color: #fff;
}

.account-btn {
  background-color: #0052d9;
}

.wechat-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #07c160;
}

.phone-btn {
  background-color: #1677ff;
  margin-top: 50rpx;
}

.wechat-btn .iconfont {
  font-size: 40rpx;
}

.switch-login {
  text-align: center;
  font-size: 26rpx;
  color: #0052d9;
  margin-top: 20rpx;
}

.footer {
  margin-top: auto;
  font-size: 24rpx;
  color: #999;
  text-align: center;
  padding: 40rpx 0;
}

.link {
  color: #0052d9;
  display: inline;
}

.debug-info {
  margin-top: 40rpx;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  border: 1px dashed #ddd;
}

.debug-title {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
  font-weight: bold;
}

.debug-text {
  display: block;
  font-size: 22rpx;
  color: #999;
  line-height: 1.5;
  margin-bottom: 6rpx;
}
</style>
